package com.todo.pro.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.todo.pro.handle.EE;

@ControllerAdvice
public class BaseControllerAdvice {

	@ExceptionHandler({ TypeMismatchException.class })
	@ResponseBody
	public Map<String, Object> errorRequest(TypeMismatchException ex) {
		ex.printStackTrace();
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", String.format(EE.SYSTEM_ERROR_6.i(), ex.getPropertyName(), ex.getRequiredType()));
		return data;
	}

	@ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
	@ResponseBody
	public Map<String, Object> errorRequest(HttpMediaTypeNotSupportedException ex) {
		ex.printStackTrace();
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", String.format(EE.SYSTEM_ERROR_5.i(), ex.getLocalizedMessage()));
		return data;
	}

	@ResponseBody
	@ExceptionHandler({ MissingServletRequestParameterException.class })
	public Map<String, Object> errorRequest(MissingServletRequestParameterException ex) {
		ex.printStackTrace();
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", String.format(EE.SYSTEM_ERROR_4.i(), ex.getParameterName()));
		return data;
	}

	@ResponseBody
	@ExceptionHandler({ HttpMessageNotReadableException.class })
	public Map<String, Object> errorRequest(HttpMessageNotReadableException ex) {
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", EE.SYSTEM_ERROR_3.i());
		return data;
	}

	@ResponseBody
	@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
	public Map<String, Object> errorRequest(HttpRequestMethodNotSupportedException ex) {
		ex.printStackTrace();
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", String.format(EE.SYSTEM_ERROR_2.i(), String.join(",", ex.getSupportedMethods())));
		return data;
	}

	@ResponseBody
	@ExceptionHandler
	public Map<String, Object> errorRequest(Exception ex) {
		ex.printStackTrace();
		Map<String, Object> data = new HashMap<>();
		data.put("code", 500);
		data.put("msg", EE.SYSTEM_ERROR_1.i());
		return data;
	}
}
